from apps.user.dao import UserDao
from apps.system.team.dao import TeamDao
from apps.user.countVerticalData import updateVerticalPerformance, updateVerticalPeopleNumber
from apps.user.countTeamDate import updateTeamPerformance

def countTeamLevelFun(order):
    _order = order
    _user  = order.user

    # 检查上级团队考核指标，更新上级团队级别
    if _user.parent:
        # 统计直推业绩
        updateVerticalPerformance('add', _user.parent, 1, _order.sellingPrice)
        # 统计团队业绩
        updateTeamPerformance('add', _user.parent, 1, _order.sellingPrice)  # 增加团队业绩
        _parent = UserDao().findOneByObjId(_user.parent.id)
        while 1:
            if _parent:
                _teams = TeamDao().findAll().order_by('-grade')
                
                for team in _teams:
                    _usersForChildCount = 0
                    if team.grade == 0:
                        continue
                    elif team.grade == 1:
                        _usersForChildCount = UserDao().findAll().filter(parent=_parent, role='custom', rank__grade__gte=1).count()
                    else:
                        _usersForChildCount = UserDao().findAll().filter(parent=_parent, role='custom', team__grade__gte=team.grade-1).count()

                    # print('用户', _parent.id, _usersForChildCount, _parent.teamPerformance)
                    # print('级别', team.grade, team.verticalPeopleNumber, team.teamPerformance)
                    if _usersForChildCount >= team.verticalPeopleNumber and _parent.teamPerformance >= team.teamPerformance:
                        if _parent.team.grade < team.grade:
                            print('满足条件升级', team.grade)
                            UserDao().update(_parent.id, {'team': team.id})
                        break
                _parent = _parent.parent
                print('_parent', _parent)
            else:
                print('上级不存在')
                break
    else:
        print('上级不存在')